<template>
  <div class="appointment-management">
    <!-- 页面标题 -->
    <div class="page-header">
      <h2>预约管理</h2>
      <p>管理患者体检预约，包括预约确认、时间安排和状态跟踪</p>
    </div>
    
    <!-- 搜索和筛选 -->
    <el-card class="search-card">
      <el-form :model="searchForm" inline class="search-form">
        <el-form-item label="患者姓名">
          <el-input
            v-model="searchForm.patientName"
            placeholder="请输入患者姓名"
            clearable
            style="width: 200px"
          />
        </el-form-item>
        
        <el-form-item label="预约状态">
          <el-select
            v-model="searchForm.status"
            placeholder="请选择状态"
            clearable
            style="width: 150px"
          >
            <el-option label="待确认" value="pending" />
            <el-option label="已确认" value="confirmed" />
            <el-option label="进行中" value="in_progress" />
            <el-option label="已完成" value="completed" />
            <el-option label="已取消" value="cancelled" />
          </el-select>
        </el-form-item>
        
        <el-form-item label="预约日期">
          <el-date-picker
            v-model="searchForm.dateRange"
            type="daterange"
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            format="YYYY-MM-DD"
            value-format="YYYY-MM-DD"
            style="width: 240px"
          />
        </el-form-item>
        
        <el-form-item label="体检套餐">
          <el-select
            v-model="searchForm.packageId"
            placeholder="请选择套餐"
            clearable
            style="width: 180px"
          >
            <el-option
              v-for="pkg in packages"
              :key="pkg.id"
              :label="pkg.name"
              :value="pkg.id"
            />
          </el-select>
        </el-form-item>
        
        <el-form-item>
          <el-button type="primary" @click="handleSearch">
            <el-icon><Search /></el-icon>
            搜索
          </el-button>
          <el-button @click="handleReset">
            <el-icon><Refresh /></el-icon>
            重置
          </el-button>
        </el-form-item>
      </el-form>
    </el-card>
    
    <!-- 操作栏 -->
    <el-card class="action-card">
      <div class="action-bar">
        <div class="action-left">
          <el-button type="primary" @click="handleCreate">
            <el-icon><Plus /></el-icon>
            新建预约
          </el-button>
          <el-button type="success" @click="handleBatchConfirm" :disabled="selectedAppointments.length === 0">
            <el-icon><Check /></el-icon>
            批量确认
          </el-button>
          <el-button type="warning" @click="handleBatchCancel" :disabled="selectedAppointments.length === 0">
            <el-icon><Close /></el-icon>
            批量取消
          </el-button>
        </div>
        
        <div class="action-right">
          <el-button @click="handleExport">
            <el-icon><Download /></el-icon>
            导出
          </el-button>
          <el-button @click="handleRefresh">
            <el-icon><Refresh /></el-icon>
            刷新
          </el-button>
        </div>
      </div>
    </el-card>
    
    <!-- 统计卡片 -->
    <div class="stats-cards">
      <el-row :gutter="20">
        <el-col :span="6">
          <el-card class="stat-card">
            <div class="stat-content">
              <div class="stat-icon pending">
                <el-icon><Clock /></el-icon>
              </div>
              <div class="stat-info">
                <div class="stat-number">{{ stats.pending }}</div>
                <div class="stat-label">待确认</div>
              </div>
            </div>
          </el-card>
        </el-col>
        
        <el-col :span="6">
          <el-card class="stat-card">
            <div class="stat-content">
              <div class="stat-icon confirmed">
                <el-icon><Check /></el-icon>
              </div>
              <div class="stat-info">
                <div class="stat-number">{{ stats.confirmed }}</div>
                <div class="stat-label">已确认</div>
              </div>
            </div>
          </el-card>
        </el-col>
        
        <el-col :span="6">
          <el-card class="stat-card">
            <div class="stat-content">
              <div class="stat-icon progress">
                <el-icon><Loading /></el-icon>
              </div>
              <div class="stat-info">
                <div class="stat-number">{{ stats.inProgress }}</div>
                <div class="stat-label">进行中</div>
              </div>
            </div>
          </el-card>
        </el-col>
        
        <el-col :span="6">
          <el-card class="stat-card">
            <div class="stat-content">
              <div class="stat-icon completed">
                <el-icon><CircleCheck /></el-icon>
              </div>
              <div class="stat-info">
                <div class="stat-number">{{ stats.completed }}</div>
                <div class="stat-label">已完成</div>
              </div>
            </div>
          </el-card>
        </el-col>
      </el-row>
    </div>
    
    <!-- 预约列表 -->
    <el-card class="table-card">
      <el-table
        v-loading="loading"
        :data="appointments"
        @selection-change="handleSelectionChange"
        @sort-change="handleSortChange"
        stripe
        style="width: 100%"
      >
        <el-table-column type="selection" width="55" />
        
        <el-table-column prop="id" label="预约ID" width="100" sortable="custom" />
        
        <el-table-column prop="patientName" label="患者姓名" width="120">
          <template #default="{ row }">
            <div class="patient-info">
              <el-avatar :size="32" :src="row.patientAvatar">
                <el-icon><User /></el-icon>
              </el-avatar>
              <div class="patient-details">
                <div class="patient-name">{{ row.patientName }}</div>
                <div class="patient-phone">{{ row.patientPhone }}</div>
              </div>
            </div>
          </template>
        </el-table-column>
        
        <el-table-column prop="packageName" label="体检套餐" width="150" show-overflow-tooltip />
        
        <el-table-column prop="appointmentDate" label="预约日期" width="120" sortable="custom">
          <template #default="{ row }">
            {{ formatDate(row.appointmentDate) }}
          </template>
        </el-table-column>
        
        <el-table-column prop="appointmentTime" label="预约时间" width="100">
          <template #default="{ row }">
            {{ row.appointmentTime }}
          </template>
        </el-table-column>
        
        <el-table-column prop="status" label="状态" width="100">
          <template #default="{ row }">
            <el-tag :type="getStatusType(row.status)" size="small">
              {{ getStatusText(row.status) }}
            </el-tag>
          </template>
        </el-table-column>
        
        <el-table-column prop="doctor" label="负责医生" width="100" show-overflow-tooltip />
        
        <el-table-column prop="createdAt" label="创建时间" width="150" sortable="custom">
          <template #default="{ row }">
            {{ formatDateTime(row.createdAt) }}
          </template>
        </el-table-column>
        
        <el-table-column prop="remark" label="备注" min-width="120" show-overflow-tooltip />
        
        <el-table-column label="操作" width="200" fixed="right">
          <template #default="{ row }">
            <div class="action-buttons">
              <el-button type="primary" size="small" text @click="handleView(row)">
                查看
              </el-button>
              
              <el-button
                v-if="row.status === 'pending'"
                type="success"
                size="small"
                text
                @click="handleConfirm(row)"
              >
                确认
              </el-button>
              
              <el-button
                v-if="['pending', 'confirmed'].includes(row.status)"
                type="warning"
                size="small"
                text
                @click="handleEdit(row)"
              >
                编辑
              </el-button>
              
              <el-button
                v-if="row.status === 'confirmed'"
                type="info"
                size="small"
                text
                @click="handleStart(row)"
              >
                开始
              </el-button>
              
              <el-dropdown trigger="click">
                <el-button type="info" size="small" text>
                  更多<el-icon><ArrowDown /></el-icon>
                </el-button>
                <template #dropdown>
                  <el-dropdown-menu>
                    <el-dropdown-item @click="handleReschedule(row)">
                      <el-icon><Calendar /></el-icon>
                      改期
                    </el-dropdown-item>
                    <el-dropdown-item
                      v-if="!['completed', 'cancelled'].includes(row.status)"
                      @click="handleCancel(row)"
                    >
                      <el-icon><Close /></el-icon>
                      取消
                    </el-dropdown-item>
                    <el-dropdown-item @click="handlePrint(row)">
                      <el-icon><Printer /></el-icon>
                      打印
                    </el-dropdown-item>
                    <el-dropdown-item
                      v-if="['pending', 'confirmed'].includes(row.status)"
                      divided
                      @click="handleDelete(row)"
                    >
                      <el-icon><Delete /></el-icon>
                      删除
                    </el-dropdown-item>
                  </el-dropdown-menu>
                </template>
              </el-dropdown>
            </div>
          </template>
        </el-table-column>
      </el-table>
      
      <!-- 分页 -->
      <div class="pagination-wrapper">
        <el-pagination
          v-model:current-page="pagination.currentPage"
          v-model:page-size="pagination.pageSize"
          :total="pagination.total"
          :page-sizes="[10, 20, 50, 100]"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>
    
    <!-- 预约表单对话框 -->
    <AppointmentForm
      v-model:visible="formVisible"
      :appointment="currentAppointment"
      :mode="formMode"
      @success="handleFormSuccess"
    />
    
    <!-- 预约详情对话框 -->
    <AppointmentDetail
      v-model:visible="detailVisible"
      :appointment="currentAppointment"
      @edit="handleEdit"
      @confirm="handleConfirm"
      @cancel="handleCancel"
    />
  </div>
</template>

<script setup>
import { ref, reactive, onMounted, computed } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import AppointmentForm from '@/components/AppointmentForm.vue'
import AppointmentDetail from '@/components/AppointmentDetail.vue'

// 响应式数据
const loading = ref(false)
const formVisible = ref(false)
const detailVisible = ref(false)
const formMode = ref('create')
const currentAppointment = ref(null)
const selectedAppointments = ref([])

// 搜索表单
const searchForm = reactive({
  patientName: '',
  status: '',
  dateRange: [],
  packageId: ''
})

// 分页
const pagination = reactive({
  currentPage: 1,
  pageSize: 20,
  total: 0
})

// 排序
const sortConfig = reactive({
  prop: 'createdAt',
  order: 'descending'
})

// 模拟数据
const appointments = ref([
  {
    id: 'A001',
    patientId: 1,
    patientName: '张三',
    patientPhone: '13800138001',
    patientAvatar: '',
    packageId: 1,
    packageName: '基础体检套餐',
    appointmentDate: '2024-01-20',
    appointmentTime: '09:00',
    status: 'pending',
    doctor: '李医生',
    remark: '患者要求上午体检',
    createdAt: '2024-01-15 10:30:00',
    updatedAt: '2024-01-15 10:30:00'
  },
  {
    id: 'A002',
    patientId: 2,
    patientName: '李四',
    patientPhone: '13800138002',
    patientAvatar: '',
    packageId: 2,
    packageName: '全面体检套餐',
    appointmentDate: '2024-01-21',
    appointmentTime: '14:00',
    status: 'confirmed',
    doctor: '王医生',
    remark: '',
    createdAt: '2024-01-14 15:20:00',
    updatedAt: '2024-01-16 09:15:00'
  },
  {
    id: 'A003',
    patientId: 3,
    patientName: '王五',
    patientPhone: '13800138003',
    patientAvatar: '',
    packageId: 1,
    packageName: '基础体检套餐',
    appointmentDate: '2024-01-19',
    appointmentTime: '10:30',
    status: 'in_progress',
    doctor: '张医生',
    remark: '需要空腹检查',
    createdAt: '2024-01-12 11:45:00',
    updatedAt: '2024-01-19 08:30:00'
  },
  {
    id: 'A004',
    patientId: 4,
    patientName: '赵六',
    patientPhone: '13800138004',
    patientAvatar: '',
    packageId: 3,
    packageName: '高端体检套餐',
    appointmentDate: '2024-01-18',
    appointmentTime: '08:30',
    status: 'completed',
    doctor: '陈医生',
    remark: '体检完成，报告已出',
    createdAt: '2024-01-10 16:20:00',
    updatedAt: '2024-01-18 17:30:00'
  },
  {
    id: 'A005',
    patientId: 5,
    patientName: '孙七',
    patientPhone: '13800138005',
    patientAvatar: '',
    packageId: 2,
    packageName: '全面体检套餐',
    appointmentDate: '2024-01-17',
    appointmentTime: '15:30',
    status: 'cancelled',
    doctor: '刘医生',
    remark: '患者临时有事取消',
    createdAt: '2024-01-08 14:10:00',
    updatedAt: '2024-01-16 20:45:00'
  }
])

const packages = ref([
  { id: 1, name: '基础体检套餐' },
  { id: 2, name: '全面体检套餐' },
  { id: 3, name: '高端体检套餐' },
  { id: 4, name: '专项体检套餐' }
])

// 统计数据
const stats = computed(() => {
  const pending = appointments.value.filter(item => item.status === 'pending').length
  const confirmed = appointments.value.filter(item => item.status === 'confirmed').length
  const inProgress = appointments.value.filter(item => item.status === 'in_progress').length
  const completed = appointments.value.filter(item => item.status === 'completed').length
  
  return {
    pending,
    confirmed,
    inProgress,
    completed
  }
})

// 生命周期
onMounted(() => {
  loadAppointments()
})

// 方法
const loadAppointments = async () => {
  loading.value = true
  try {
    // 模拟API调用
    await new Promise(resolve => setTimeout(resolve, 500))
    pagination.total = appointments.value.length
  } catch (error) {
    ElMessage.error('加载预约列表失败')
  } finally {
    loading.value = false
  }
}

const handleSearch = () => {
  pagination.currentPage = 1
  loadAppointments()
}

const handleReset = () => {
  Object.assign(searchForm, {
    patientName: '',
    status: '',
    dateRange: [],
    packageId: ''
  })
  handleSearch()
}

const handleRefresh = () => {
  loadAppointments()
}

const handleCreate = () => {
  currentAppointment.value = null
  formMode.value = 'create'
  formVisible.value = true
}

const handleEdit = (appointment) => {
  currentAppointment.value = { ...appointment }
  formMode.value = 'edit'
  formVisible.value = true
}

const handleView = (appointment) => {
  currentAppointment.value = appointment
  detailVisible.value = true
}

const handleConfirm = async (appointment) => {
  try {
    await ElMessageBox.confirm(
      `确定要确认预约 ${appointment.id} 吗？`,
      '确认预约',
      {
        confirmButtonText: '确认',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )
    
    // 模拟API调用
    appointment.status = 'confirmed'
    appointment.updatedAt = new Date().toLocaleString('zh-CN')
    
    ElMessage.success('预约确认成功')
  } catch {
    // 用户取消
  }
}

const handleStart = async (appointment) => {
  try {
    await ElMessageBox.confirm(
      `确定要开始体检 ${appointment.id} 吗？`,
      '开始体检',
      {
        confirmButtonText: '开始',
        cancelButtonText: '取消',
        type: 'info'
      }
    )
    
    // 模拟API调用
    appointment.status = 'in_progress'
    appointment.updatedAt = new Date().toLocaleString('zh-CN')
    
    ElMessage.success('体检已开始')
  } catch {
    // 用户取消
  }
}

const handleCancel = async (appointment) => {
  try {
    const { value: reason } = await ElMessageBox.prompt(
      '请输入取消原因',
      '取消预约',
      {
        confirmButtonText: '确认取消',
        cancelButtonText: '取消',
        inputPlaceholder: '请输入取消原因',
        inputValidator: (value) => {
          if (!value || value.trim() === '') {
            return '请输入取消原因'
          }
          return true
        }
      }
    )
    
    // 模拟API调用
    appointment.status = 'cancelled'
    appointment.remark = `取消原因：${reason}`
    appointment.updatedAt = new Date().toLocaleString('zh-CN')
    
    ElMessage.success('预约已取消')
  } catch {
    // 用户取消
  }
}

const handleReschedule = (appointment) => {
  ElMessage.info(`改期功能待实现 - 预约ID: ${appointment.id}`)
}

const handlePrint = (appointment) => {
  ElMessage.info(`打印功能待实现 - 预约ID: ${appointment.id}`)
}

const handleDelete = async (appointment) => {
  try {
    await ElMessageBox.confirm(
      `确定要删除预约 ${appointment.id} 吗？此操作不可恢复。`,
      '删除预约',
      {
        confirmButtonText: '删除',
        cancelButtonText: '取消',
        type: 'error'
      }
    )
    
    // 模拟API调用
    const index = appointments.value.findIndex(item => item.id === appointment.id)
    if (index > -1) {
      appointments.value.splice(index, 1)
      pagination.total--
    }
    
    ElMessage.success('预约删除成功')
  } catch {
    // 用户取消
  }
}

const handleBatchConfirm = async () => {
  try {
    await ElMessageBox.confirm(
      `确定要批量确认选中的 ${selectedAppointments.value.length} 个预约吗？`,
      '批量确认',
      {
        confirmButtonText: '确认',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )
    
    // 模拟API调用
    selectedAppointments.value.forEach(appointment => {
      if (appointment.status === 'pending') {
        appointment.status = 'confirmed'
        appointment.updatedAt = new Date().toLocaleString('zh-CN')
      }
    })
    
    ElMessage.success('批量确认成功')
    selectedAppointments.value = []
  } catch {
    // 用户取消
  }
}

const handleBatchCancel = async () => {
  try {
    const { value: reason } = await ElMessageBox.prompt(
      '请输入批量取消原因',
      '批量取消',
      {
        confirmButtonText: '确认取消',
        cancelButtonText: '取消',
        inputPlaceholder: '请输入取消原因',
        inputValidator: (value) => {
          if (!value || value.trim() === '') {
            return '请输入取消原因'
          }
          return true
        }
      }
    )
    
    // 模拟API调用
    selectedAppointments.value.forEach(appointment => {
      if (['pending', 'confirmed'].includes(appointment.status)) {
        appointment.status = 'cancelled'
        appointment.remark = `批量取消原因：${reason}`
        appointment.updatedAt = new Date().toLocaleString('zh-CN')
      }
    })
    
    ElMessage.success('批量取消成功')
    selectedAppointments.value = []
  } catch {
    // 用户取消
  }
}

const handleExport = () => {
  ElMessage.info('导出功能待实现')
}

const handleSelectionChange = (selection) => {
  selectedAppointments.value = selection
}

const handleSortChange = ({ prop, order }) => {
  sortConfig.prop = prop
  sortConfig.order = order
  loadAppointments()
}

const handleSizeChange = (size) => {
  pagination.pageSize = size
  pagination.currentPage = 1
  loadAppointments()
}

const handleCurrentChange = (page) => {
  pagination.currentPage = page
  loadAppointments()
}

const handleFormSuccess = () => {
  formVisible.value = false
  loadAppointments()
}

const getStatusType = (status) => {
  const statusMap = {
    pending: 'warning',
    confirmed: 'primary',
    in_progress: 'primary',
    completed: 'success',
    cancelled: 'danger'
  }
  return statusMap[status] || 'info'
}

const getStatusText = (status) => {
  const statusMap = {
    pending: '待确认',
    confirmed: '已确认',
    in_progress: '进行中',
    completed: '已完成',
    cancelled: '已取消'
  }
  return statusMap[status] || '未知'
}

const formatDate = (date) => {
  if (!date) return ''
  return new Date(date).toLocaleDateString('zh-CN')
}

const formatDateTime = (dateTime) => {
  if (!dateTime) return ''
  const date = new Date(dateTime)
  return date.toLocaleString('zh-CN', {
    year: 'numeric',
    month: '2-digit',
    day: '2-digit',
    hour: '2-digit',
    minute: '2-digit'
  })
}
</script>

<style scoped>
.appointment-management {
  padding: 20px;
}

.page-header {
  margin-bottom: 20px;
}

.page-header h2 {
  margin: 0 0 8px 0;
  color: #2c3e50;
  font-size: 24px;
  font-weight: 600;
}

.page-header p {
  margin: 0;
  color: #606266;
  font-size: 14px;
}

.search-card,
.action-card,
.table-card {
  margin-bottom: 20px;
}

.search-form {
  margin: 0;
}

.action-bar {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.action-left,
.action-right {
  display: flex;
  gap: 12px;
}

.stats-cards {
  margin-bottom: 20px;
}

.stat-card {
  cursor: pointer;
  transition: all 0.3s ease;
}

.stat-card:hover {
  transform: translateY(-2px);
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
}

.stat-content {
  display: flex;
  align-items: center;
  gap: 16px;
}

.stat-icon {
  width: 48px;
  height: 48px;
  border-radius: 12px;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 24px;
  color: white;
}

.stat-icon.pending {
  background: linear-gradient(135deg, #f39c12, #e67e22);
}

.stat-icon.confirmed {
  background: linear-gradient(135deg, #3498db, #2980b9);
}

.stat-icon.progress {
  background: linear-gradient(135deg, #9b59b6, #8e44ad);
}

.stat-icon.completed {
  background: linear-gradient(135deg, #27ae60, #229954);
}

.stat-info {
  flex: 1;
}

.stat-number {
  font-size: 24px;
  font-weight: 600;
  color: #2c3e50;
  line-height: 1;
  margin-bottom: 4px;
}

.stat-label {
  font-size: 14px;
  color: #606266;
}

.patient-info {
  display: flex;
  align-items: center;
  gap: 12px;
}

.patient-details {
  flex: 1;
  min-width: 0;
}

.patient-name {
  font-weight: 500;
  color: #2c3e50;
  font-size: 14px;
  line-height: 1.2;
}

.patient-phone {
  color: #909399;
  font-size: 12px;
  line-height: 1.2;
}

.action-buttons {
  display: flex;
  gap: 8px;
  flex-wrap: wrap;
}

.pagination-wrapper {
  display: flex;
  justify-content: center;
  margin-top: 20px;
}

/* 响应式设计 */
@media (max-width: 1200px) {
  .search-form {
    flex-direction: column;
    align-items: flex-start;
  }
  
  .search-form .el-form-item {
    margin-right: 0;
    margin-bottom: 12px;
  }
  
  .action-bar {
    flex-direction: column;
    gap: 12px;
    align-items: stretch;
  }
  
  .action-left,
  .action-right {
    justify-content: center;
  }
}

@media (max-width: 768px) {
  .appointment-management {
    padding: 10px;
  }
  
  .stats-cards .el-col {
    margin-bottom: 12px;
  }
  
  .stat-content {
    gap: 12px;
  }
  
  .stat-icon {
    width: 40px;
    height: 40px;
    font-size: 20px;
  }
  
  .stat-number {
    font-size: 20px;
  }
  
  .patient-info {
    flex-direction: column;
    align-items: flex-start;
    gap: 8px;
  }
  
  .action-buttons {
    flex-direction: column;
    gap: 4px;
  }
  
  .action-buttons .el-button {
    width: 100%;
    justify-content: center;
  }
  
  :deep(.el-table) {
    font-size: 12px;
  }
  
  :deep(.el-table .cell) {
    padding: 8px 4px;
  }
}

@media (max-width: 480px) {
  .page-header h2 {
    font-size: 20px;
  }
  
  .action-left,
  .action-right {
    flex-direction: column;
  }
  
  .action-left .el-button,
  .action-right .el-button {
    width: 100%;
  }
  
  .stat-content {
    flex-direction: column;
    text-align: center;
    gap: 8px;
  }
  
  .pagination-wrapper {
    overflow-x: auto;
  }
  
  :deep(.el-pagination) {
    justify-content: center;
    flex-wrap: wrap;
  }
}
</style>